package com.d3works.apps.account.service.analytic;

import com.d3works.apps.account.db.AnalyticAccount;
import com.d3works.apps.account.db.AnalyticAxis;
import com.d3works.apps.account.db.AnalyticMoveLine;
import com.d3works.apps.account.service.app.AppAccountService;
import com.d3works.apps.account.service.config.AccountConfigService;
import com.d3works.apps.base.db.Company;
import com.d3works.exception.D3worksException;
import java.math.BigDecimal;
import java.util.List;
import javax.inject.Inject;
import org.apache.commons.collections.CollectionUtils;

public class AnalyticToolServiceImpl implements AnalyticToolService {

  protected AppAccountService appAccountService;
  protected AccountConfigService accountConfigService;

  @Inject
  public AnalyticToolServiceImpl(
      AppAccountService appAccountService, AccountConfigService accountConfigService) {
    this.appAccountService = appAccountService;
    this.accountConfigService = accountConfigService;
  }

  @Override
  public boolean isManageAnalytic(Company company) throws D3worksException {
    return appAccountService.getAppAccount().getManageAnalyticAccounting()
        && company != null
        && accountConfigService.getAccountConfig(company).getManageAnalyticAccounting();
  }

  @Override
  public boolean isPositionUnderAnalyticAxisSelect(Company company, int position)
      throws D3worksException {
    return company != null
        && position <= accountConfigService.getAccountConfig(company).getNbrOfAnalyticAxisSelect();
  }

  @Override
  public boolean isAxisAccountSumValidated(
      List<AnalyticMoveLine> analyticMoveLineList, AnalyticAxis analyticAxis) {
    if (!CollectionUtils.isEmpty(analyticMoveLineList)) {
      BigDecimal sum = BigDecimal.ZERO;
      for (AnalyticMoveLine analyticMoveLine : analyticMoveLineList) {
        if (analyticMoveLine.getAnalyticAxis().equals(analyticAxis)) {
          sum = sum.add(analyticMoveLine.getPercentage());
        }
      }
      return sum.compareTo(new BigDecimal(100)) == 0;
    }
    return true;
  }

  @Override
  public boolean isAnalyticAxisFilled(
      AnalyticAccount analyticAccount, List<AnalyticMoveLine> analyticMoveLineList) {
    return analyticAccount != null
        && !isAxisAccountSumValidated(analyticMoveLineList, analyticAccount.getAnalyticAxis());
  }
}
